/**
 * Copyright (c) [2022] [yanyeori]
 * [yanyeori-service] is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.yanyeori.service.file.business.controller;

import com.yanyeori.framework.core.model.WebResponse;
import com.yanyeori.service.file.api.dto.FileDTO;
import com.yanyeori.service.file.business.exception.FileException;
import com.yanyeori.service.file.business.service.OssFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * OSS文件客户端
 *
 * @author chenkuan
 * @since 2022/10/6 14:43
 */
@RestController
@RequestMapping("/ossFileController")
public class OssFileController {

    @Autowired
    private OssFileService ossFileService;

    /**
     * OSS文件上传接口
     *
     * @param file 上传的文件
     * @return 文件上传信息
     */
    @PostMapping("/upload")
    public WebResponse<FileDTO> upload(@RequestPart("file") MultipartFile file) {
        try {
            FileDTO fileDTO = ossFileService.upload(file);
            return WebResponse.ok(fileDTO);
        } catch (IOException e) {
            throw new FileException(e, "文件[{}]上传失败", file.getOriginalFilename());
        }
    }

    /**
     * 获取OSS文件下载链接
     *
     * @param filePath 文件路径
     * @return 访问地址
     */
    @GetMapping("/getDownloadUrl")
    public WebResponse<String> getDownloadUrl(@RequestParam("filePath") String filePath) {
        return WebResponse.ok(ossFileService.getDownloadUrl(filePath));
    }
}
